package com.zjzywl.smoke.controller;

import com.zjzywl.smoke.config.AppConfig;

import java.io.File;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.zjzywl.smoke.entity.Organization;
import com.zjzywl.smoke.entity.dto.OrganizationCountDto;
import com.zjzywl.smoke.util.WebResult;

@Controller
@RequestMapping(value = "/organization")
public class OrganizationController extends BaseController {
    @Autowired
    private AppConfig appConfig;

    // 获取组织列表
    @RequestMapping(value = "/list")
    @ResponseBody
    public WebResult getOrganizations(@PathParam("type") String type) {
        String loginName = this.getLoginUser().getPeople().getLoginName();
        ResponseEntity<Object> orgs = appConfig.restTemplate().getForEntity(
                appConfig.getGetDataIp() + "/organization/data/list?loginName=" + loginName + "&type=" + type,
                Object.class);
        return WebResult.OK(orgs);
    }

    // 获取单个组织
    @ResponseBody
    @RequestMapping(value = "/edit/id/{id}")
    public WebResult editOrganizationById(@PathVariable Integer id) {
        ResponseEntity<Organization> org = appConfig.restTemplate()
                .getForEntity(appConfig.getGetDataIp() + "/organization/edit/id/" + id, Organization.class);
        return WebResult.OK(org);
    }

    // 获取单个组织下的所有组织
    @ResponseBody
    @RequestMapping(value = "/getAll")
    public WebResult editOrganizationAllById(@PathParam("id") String id) {
        ResponseEntity<Organization[]> org = appConfig.restTemplate()
                .getForEntity(appConfig.getGetDataIp() + "/organization/getByPath/" + id, Organization[].class);
        return WebResult.OK(org);
    }

    // 保存组织信息
    @PostMapping(value = "/save")
    @ResponseBody
    public WebResult save(Organization org, @PathParam("parentid") Integer parentid, MultipartFile file) {
        try {
            if(file!=null) {
                org = executeUpload(org, file);
            }
            ResponseEntity<Organization> history = appConfig.restTemplate().postForEntity(
                    appConfig.getGetDataIp() + "/organization/save?parentid=" + parentid, org,
                    Organization.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            // 打印出错
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }

    }

    // 删除组织信息
    @RequestMapping(value = "/delete/{id}")
    @ResponseBody
    public WebResult delete(@PathVariable("id") String id) {
        ResponseEntity<String> org = appConfig.restTemplate()
                .getForEntity(appConfig.getGetDataIp() + "/organization/delete/" + id, String.class);
        return WebResult.OK(org);

    }

    // 获取消防站列表当前页
    @RequestMapping(value = "/organizationfire/all")
    @ResponseBody
    public WebResult getOrganizationData(@PathParam("type") String type) {
        String loginName = this.getLoginUser().getPeople().getLoginName();
        ResponseEntity<Object> orgs = appConfig.restTemplate().getForEntity(appConfig.getGetDataIp()
                + "/organization/organizationfire/all?loginName=" + loginName + "&type=" + type, Object.class);
        return WebResult.OK(orgs);
    }

    // 组织唯一性验证
    @RequestMapping(value = "/org/validateName")
    @ResponseBody
    public ResponseEntity<String> checkUserName(@PathParam("orgName") String orgName,
            @PathParam("originalOrgName") String originalOrgName) {
        ResponseEntity<String> users = appConfig.restTemplate().postForEntity(appConfig.getGetDataIp()
                + "/organization/org/validateName?orgName=" + orgName + "&originalOrgName=" + originalOrgName, null,
                String.class);
        return users;

    }

    // 获取组织列表 后面有设备count
    @RequestMapping(value = "/data/list/count")
    @ResponseBody
    public WebResult getOrganizationAndCount(HttpServletRequest request) {
        String loginName = this.getLoginUser().getPeople().getLoginName();
        ResponseEntity<OrganizationCountDto[]> ocd = appConfig.restTemplate().getForEntity(appConfig.getGetDataIp()
                + "/organization/data/list/count?loginName=" + loginName + "&" + request.getQueryString(),
                OrganizationCountDto[].class);
        return WebResult.OK(ocd);
    }

    /*
     * 图片上传方法
     * 
     */
    private Organization executeUpload(Organization org, MultipartFile file) throws Exception {
        String uploadDir = getUploadDir() + org.getOrgid() + "/";
        // 如果文件不存在，自动创建文件夹
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                logger.error("创建上传目录失败");
            }
        }
        if (file != null) {
            // 文件后缀名
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 上传文件名
            String filename = UUID.randomUUID() + suffix;
            // 服务器端保存的文件对象
            File serverFile = new File(uploadDir + filename);
            // 将上传到的文件写入到服务器
            file.transferTo(serverFile);
            org.setPhotoUrl("/upload/" + org.getOrgid() + "/" + filename);
        }
        return org;
    }
}
